import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { setLocale } from '../locales'

export const useSettingsStore = defineStore('settings', () => {
  // 默认设置
  const defaultSettings = {
    // 通用设置
    theme: 'light',
    language: 'zh-CN',
    startMinimized: false,
    minimizeOnClose: false,
    
    // 安全设置
    autoLock: true,
    autoLockTime: 5, // 分钟
    requirePasswordOnStart: true,
    autoClearClipboard: true,
    clipboardClearTime: 30, // 秒
    showPasswordStrength: true,
    checkDuplicatePasswords: true,
    checkWeakPasswords: true,
    
    // 备份设置
    autoBackup: true,
    backupFrequency: 'weekly',
    maxBackups: 10,
    backupPath: ''
  }

  // 当前设置
  const settings = ref({ ...defaultSettings })
  
  // 自动锁定相关
  const isLocked = ref(false)
  const lastActivityTime = ref(Date.now())
  const autoLockTimer = ref(null)
  const activityListeners = ref([])
  
  // 剪贴板清理相关
  const clipboardTimers = ref(new Map())
  
  // 主题相关
  const isDarkMode = computed(() => {
    if (settings.value.theme === 'dark') return true
    if (settings.value.theme === 'light') return false
    // 跟随系统
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  })

  // 加载设置
  const loadSettings = async () => {
    try {
      const savedSettings = localStorage.getItem('passwordManagerSettings')
      if (savedSettings) {
        const parsed = JSON.parse(savedSettings)
        settings.value = { ...defaultSettings, ...parsed }
      }
      
      // 加载主进程设置
      if (window.electronAPI?.loadAppSettings) {
        const appSettings = await window.electronAPI.loadAppSettings()
        if (appSettings) {
          settings.value.startMinimized = appSettings.startMinimized
          settings.value.minimizeOnClose = appSettings.minimizeOnClose
          settings.value.language = appSettings.language
        }
      }
      
      // 应用设置
      setLocale(settings.value.language)
      applyTheme()
      setupAutoLock()
      
    } catch (error) {
      console.error('加载设置失败:', error)
      ElMessage.error('加载设置失败，将使用默认设置')
      settings.value = { ...defaultSettings }
    }
  }

  // 保存设置
  const saveSettings = async () => {
    try {
      localStorage.setItem('passwordManagerSettings', JSON.stringify(settings.value))
      
      // 保存主进程设置
      if (window.electronAPI?.saveAppSettings) {
        await window.electronAPI.saveAppSettings({
          startMinimized: settings.value.startMinimized,
          minimizeOnClose: settings.value.minimizeOnClose,
          language: settings.value.language
        })
      }
      
      // 重新应用设置
      setLocale(settings.value.language)
      applyTheme()
      setupAutoLock()
      
      return true
    } catch (error) {
      console.error('保存设置失败:', error)
      ElMessage.error('保存设置失败')
      return false
    }
  }

  // 重置设置
  const resetSettings = () => {
    settings.value = { ...defaultSettings }
    applyTheme()
    setupAutoLock()
  }

  // 更新单个设置
  const updateSetting = (key, value) => {
    settings.value[key] = value
    saveSettings()
  }

  // 应用主题
  const applyTheme = () => {
    const html = document.documentElement
    const body = document.body
    const app = document.getElementById('app')
    
    // 移除所有主题类
    html.classList.remove('dark', 'light')
    body.classList.remove('dark-theme', 'light-theme')
    if (app) {
      app.classList.remove('dark', 'light')
    }
    
    if (settings.value.theme === 'dark') {
      html.classList.add('dark')
      body.classList.add('dark-theme')
      if (app) app.classList.add('dark')
    } else if (settings.value.theme === 'light') {
      html.classList.add('light')
      body.classList.add('light-theme')
      if (app) app.classList.add('light')
    } else {
      // 跟随系统
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      if (prefersDark) {
        html.classList.add('dark')
        body.classList.add('dark-theme')
        if (app) app.classList.add('dark')
      } else {
        html.classList.add('light')
        body.classList.add('light-theme')
        if (app) app.classList.add('light')
      }
    }

    // 强制更新CSS变量
    if (isDarkMode.value) {
      document.documentElement.style.setProperty('--el-bg-color', '#3c3c3c')
      document.documentElement.style.setProperty('--el-text-color-primary', '#ffffff')
      document.documentElement.style.setProperty('--el-border-color', '#555555')
    } else {
      document.documentElement.style.removeProperty('--el-bg-color')
      document.documentElement.style.removeProperty('--el-text-color-primary')
      document.documentElement.style.removeProperty('--el-border-color')
    }
  }

  // 设置自动锁定
  const setupAutoLock = () => {
    // 清除现有定时器和监听器
    if (autoLockTimer.value) {
      clearTimeout(autoLockTimer.value)
      autoLockTimer.value = null
    }

    // 移除现有监听器
    activityListeners.value.forEach(({ event, handler }) => {
      document.removeEventListener(event, handler)
    })
    activityListeners.value = []

    if (!settings.value.autoLock) return

    // 重置活动时间
    const resetActivity = () => {
      lastActivityTime.value = Date.now()
      
      // 清除现有定时器
      if (autoLockTimer.value) {
        clearTimeout(autoLockTimer.value)
      }
      
      // 设置新的定时器
      autoLockTimer.value = setTimeout(() => {
        if (!isLocked.value) {
          lockApplication()
        }
      }, settings.value.autoLockTime * 60 * 1000) // 转换为毫秒
    }

    // 监听用户活动
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click']
    events.forEach(event => {
      const handler = resetActivity
      document.addEventListener(event, handler, { passive: true })
      activityListeners.value.push({ event, handler })
    })

    // 初始化定时器
    resetActivity()
  }

  // 锁定应用
  const lockApplication = () => {
    isLocked.value = true
    
    // 触发全局锁定事件
    window.dispatchEvent(new CustomEvent('app-lock'))
    
    ElMessage.info('应用已自动锁定')
  }

  // 解锁应用
  const unlockApplication = () => {
    isLocked.value = false
    lastActivityTime.value = Date.now()
    
    // 重新设置自动锁定
    if (settings.value.autoLock) {
      setupAutoLock()
    }
  }

  // 安全复制到剪贴板
  const secureClipboardCopy = async (text, description = '密码') => {
    try {
      // 复制到剪贴板
      if (window.electronAPI && window.electronAPI.copyToClipboard) {
        await window.electronAPI.copyToClipboard(text)
      } else {
        await navigator.clipboard.writeText(text)
      }
      
      ElMessage.success(`${description}已复制到剪贴板`)
      
      // 如果启用了自动清除剪贴板
      if (settings.value.autoClearClipboard) {
        const timerId = setTimeout(async () => {
          try {
            // 清除剪贴板
            if (window.electronAPI && window.electronAPI.copyToClipboard) {
              await window.electronAPI.copyToClipboard('')
            } else {
              await navigator.clipboard.writeText('')
            }
            
            // 从定时器映射中移除
            clipboardTimers.value.delete(timerId)
            
            ElMessage.info('剪贴板已自动清除')
          } catch (error) {
            console.error('清除剪贴板失败:', error)
          }
        }, settings.value.clipboardClearTime * 1000)
        
        // 存储定时器ID
        clipboardTimers.value.set(timerId, {
          text,
          description,
          timestamp: Date.now()
        })
      }
      
    } catch (error) {
      console.error('复制到剪贴板失败:', error)
      ElMessage.error('复制失败')
    }
  }

  // 清除所有剪贴板定时器
  const clearAllClipboardTimers = () => {
    clipboardTimers.value.forEach((_, timerId) => {
      clearTimeout(timerId)
    })
    clipboardTimers.value.clear()
  }

  // 获取备份路径
  const getBackupPath = () => {
    if (settings.value.backupPath) {
      return settings.value.backupPath
    }
    
    // 默认备份路径
    const userHome = window.electronAPI ? 
      require('os').homedir() : 
      '~/Documents'
    
    return `${userHome}/PasswordManager/Backups`
  }

  // 检查是否需要自动备份
  const shouldAutoBackup = () => {
    if (!settings.value.autoBackup) return false
    
    const lastBackup = localStorage.getItem('lastAutoBackup')
    if (!lastBackup) return true
    
    const lastBackupTime = new Date(lastBackup)
    const now = new Date()
    
    switch (settings.value.backupFrequency) {
      case 'daily':
        return (now - lastBackupTime) > 24 * 60 * 60 * 1000
      case 'weekly':
        return (now - lastBackupTime) > 7 * 24 * 60 * 60 * 1000
      case 'monthly':
        return (now - lastBackupTime) > 30 * 24 * 60 * 60 * 1000
      default:
        return false
    }
  }

  // 记录备份时间
  const recordBackupTime = () => {
    localStorage.setItem('lastAutoBackup', new Date().toISOString())
  }

  // 获取语言配置
  const getLanguageConfig = () => {
    const languages = {
      'zh-CN': {
        name: '简体中文',
        locale: 'zh-cn'
      },
      'en-US': {
        name: 'English',
        locale: 'en'
      }
    }
    
    return languages[settings.value.language] || languages['zh-CN']
  }

  // 监听主题变化
  watch(() => settings.value.theme, () => {
    applyTheme()
  })

  // 监听系统主题变化
  if (typeof window !== 'undefined') {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      if (settings.value.theme === 'auto') {
        applyTheme()
      }
    })
  }

  // 监听自动锁定设置变化
  watch(() => [settings.value.autoLock, settings.value.autoLockTime], () => {
    setupAutoLock()
  })

  // 清理函数
  const cleanup = () => {
    // 清除自动锁定定时器
    if (autoLockTimer.value) {
      clearTimeout(autoLockTimer.value)
    }
    
    // 移除事件监听器
    activityListeners.value.forEach(({ event, handler }) => {
      document.removeEventListener(event, handler)
    })
    
    // 清除剪贴板定时器
    clearAllClipboardTimers()
  }

  return {
    // 状态
    settings,
    isLocked,
    lastActivityTime,
    isDarkMode,
    
    // 方法
    loadSettings,
    saveSettings,
    resetSettings,
    updateSetting,
    applyTheme,
    setupAutoLock,
    lockApplication,
    unlockApplication,
    secureClipboardCopy,
    clearAllClipboardTimers,
    getBackupPath,
    shouldAutoBackup,
    recordBackupTime,
    getLanguageConfig,
    cleanup,
    
    // 计算属性
    clipboardTimers: computed(() => clipboardTimers.value)
  }
})
